package com.bruce.ai.alibaba.agentcard.discovery.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.bruce.ai.alibaba.agentcard.discovery.client.A2AClient;
import com.bruce.ai.alibaba.agentcard.discovery.model.A2AResponse;
import com.alibaba.nacos.api.ai.AiService;
import com.alibaba.nacos.api.ai.model.a2a.AgentCard;
import jakarta.annotation.Resource;


@Component
public class AgentCardDiscoveryRunner implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(AgentCardDiscoveryRunner.class);

    @Resource
    private A2AClient a2AClient;
    
    @Resource
    private AiService aiService;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("AgentCardDiscoveryRunner run");
        
        try {
            // 从 Nacos 发现 asurada Agent
            logger.info("开始从 Nacos 发现 asurada Agent...");
            AgentCard agentCard = aiService.getAgentCard("asurada");
            
            if (agentCard != null) {
                logger.info("成功从 Nacos 发现 asurada Agent:");
                logger.info("  名称: {}", agentCard.getName());
                logger.info("  描述: {}", agentCard.getDescription());
                logger.info("  URL: {}", agentCard.getUrl());
                logger.info("  版本: {}", agentCard.getVersion());
                logger.info("  协议版本: {}", agentCard.getProtocolVersion());
                
                // 测试 A2A 通信
                logger.info("开始测试 A2A 通信...");
                A2AResponse response = a2AClient.call("介绍一下你自己");
                logger.info("A2A 通信测试结果: {}", response);
            } else {
                logger.warn("未能从 Nacos 发现 asurada Agent");
            }
        } catch (Exception e) {
            logger.error("从 Nacos 发现 Agent 失败: {}", e.getMessage(), e);
            // 继续尝试直接 A2A 通信
            logger.info("尝试直接 A2A 通信...");
            A2AResponse response = a2AClient.call("介绍一下你自己");
            logger.info("直接 A2A 通信结果: {}", response);
        }
    }
}
